import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Base64;
import java.util.zip.Inflater;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * 调用API并尝试解密响应
 * 使用已知的Frida捕获的密钥
 */
public class DecryptAPIResponse {
    
    // API端点
    private static final String API_URL = "http://120.27.155.222:9999/api/message/send-test";
    
    // 从之前Frida Hook捕获的已知密钥（示例）
    // 你需要替换为实际捕获到的密钥
    private static final String[] KNOWN_KEYS = {
        "a1b2c3d4e5f67890123456789012345678901234567890123456789012345678", // 示例密钥1
        "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", // 示例密钥2
        // 在这里添加更多从Frida捕获的密钥
    };
    
    public static void main(String[] args) {
        System.out.println("=" + "=".repeat(99));
        System.out.println("调用数美API并尝试解密");
        System.out.println("=" + "=".repeat(99));
        System.out.println();
        
        try {
            // 1. 调用API
            System.out.println("[1/3] 正在调用API: " + API_URL);
            String response = callAPI();
            System.out.println("✅ API调用成功");
            System.out.println();
            
            // 2. 解析JSON (简单的正则提取)
            System.out.println("[2/3] 解析响应JSON...");
            
            String dev = extractJsonValue(response, "dev");
            String lastBox = extractJsonValue(response, "last_box");
            
            System.out.println("完整响应:");
            System.out.println(response);
            System.out.println();
            System.out.println("dev (Base64): " + dev);
            System.out.println("last_box (Base64): " + lastBox);
            System.out.println();
            
            // 3. 尝试用已知密钥解密
            System.out.println("[3/3] 尝试使用已知密钥解密...");
            System.out.println("=".repeat(100));
            
            boolean success = false;
            for (int i = 0; i < KNOWN_KEYS.length; i++) {
                String keyHex = KNOWN_KEYS[i];
                System.out.println("\n尝试密钥 " + (i + 1) + "/" + KNOWN_KEYS.length + ":");
                System.out.println("  密钥: " + keyHex);
                
                if (tryDecrypt(dev, keyHex)) {
                    System.out.println("\n🎉🎉🎉 成功！找到正确的密钥！");
                    System.out.println("正确的密钥: " + keyHex);
                    success = true;
                    break;
                }
            }
            
            if (!success) {
                System.out.println("\n" + "=".repeat(100));
                System.out.println("❌ 所有已知密钥都无法解密");
                System.out.println("=".repeat(100));
                System.out.println("\n💡 你需要:");
                System.out.println("   1. 运行Frida Hook脚本来捕获新的密钥");
                System.out.println("   2. 将捕获的密钥添加到 KNOWN_KEYS 数组中");
                System.out.println("   3. 重新运行此程序");
                System.out.println();
                System.out.println("或者直接运行:");
                System.out.println("   java DecryptWithCapturedKey");
                System.out.println("然后手动输入从Frida捕获的密钥");
            }
            
        } catch (Exception e) {
            System.err.println("\n❌ 错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static String callAPI() throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        
        int responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            throw new Exception("API返回错误: HTTP " + responseCode);
        }
        
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        
        return response.toString();
    }
    
    private static boolean tryDecrypt(String base64Data, String keyHex) {
        try {
            // 转换密钥
            byte[] aesKey = hexToBytes(keyHex);
            
            // Base64解码
            byte[] dataWithIV = Base64.getDecoder().decode(base64Data);
            
            // 提取IV和密文
            byte[] iv = Arrays.copyOfRange(dataWithIV, 0, 16);
            byte[] encrypted = Arrays.copyOfRange(dataWithIV, 16, dataWithIV.length);
            
            // AES解密
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            
            byte[] decrypted = cipher.doFinal(encrypted);
            
            // zlib解压
            Inflater inflater = new Inflater(true);
            inflater.setInput(decrypted);
            
            byte[] decompressed = new byte[1024 * 100];
            int decompressedLen = inflater.inflate(decompressed);
            inflater.end();
            
            // 转换为字符串
            String json = new String(decompressed, 0, decompressedLen, "UTF-8");
            
            // 成功！
            System.out.println("\n  ✅ 解密成功！");
            System.out.println("\n  解密后的数据:");
            System.out.println("  " + "-".repeat(96));
            System.out.println("  " + json);
            System.out.println("  " + "-".repeat(96));
            
            return true;
            
        } catch (Exception e) {
            System.out.println("  ❌ 失败: " + e.getClass().getSimpleName());
            return false;
        }
    }
    
    private static byte[] hexToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                                + Character.digit(hex.charAt(i+1), 16));
        }
        return data;
    }
    
    private static String extractJsonValue(String json, String key) {
        // 简单的JSON值提取: "key":"value"
        Pattern pattern = Pattern.compile("\"" + key + "\"\\s*:\\s*\"([^\"]+)\"");
        Matcher matcher = pattern.matcher(json);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
}

